package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.DbdkExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Ksda;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Yfd;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDbdk;
import cn.stylefeng.guns.sys.modular.system.entity.BtyElmsxf;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDbdkMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDbdkParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDywhParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyElmsxfParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDbdkResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDywhResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyElmsxfResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyDbdkService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 控制器
 *
 * @author liuy
 * @Date 2022-01-25 16:16:48
 */
@Controller
@RequestMapping("/btyDbdk")
public class BtyDbdkController extends BaseController {

    private String PREFIX = "/modular/system/btyDbdk";

    @Autowired
    private BtyDbdkService btyDbdkService;
    @Resource
    private BtyDbdkMapper dbdkMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyDbdk.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyDbdk_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyDbdk_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyDbdkParam btyDbdkParam) {
        this.btyDbdkService.add(btyDbdkParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyDbdkParam btyDbdkParam) {
        this.btyDbdkService.update(btyDbdkParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyDbdkParam btyDbdkParam) {
        this.btyDbdkService.delete(btyDbdkParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyDbdkParam btyDbdkParam) {
        BtyDbdk detail = this.btyDbdkService.getById(btyDbdkParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-01-25
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyDbdkParam btyDbdkParam) {
        return this.btyDbdkService.findPageBySpec(btyDbdkParam);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file,BtyDbdkParam param) {
        JsonResult jsonResult = new JsonResult();
        if(ToolUtil.isEmpty(param.getZdrq())){
            jsonResult.setState(0);
            jsonResult.setErrmsg("请先选择制单日期！");
            return jsonResult;
        }
        //导入之前删掉之前的数据
        dbdkMapper.delete(new QueryWrapper<BtyDbdk>());
        String zdrq=param.getZdrq();
        try {
            DbdkExcelListener basicExcelListener = new DbdkExcelListener(btyDbdkService);
            EasyExcel.read(file.getInputStream(), BtyDbdk.class, basicExcelListener).sheet(0).doRead();
            //导入成功之后生成调拨打款凭证
            List<BtyDbdkResult> list=btyDbdkService.dbdkList();
            for (BtyDbdkResult dbdkResult : list) {
                BigDecimal tbje=dbdkResult.getAmount();
                String bh=dbdkResult.getBh();
                String yhk=dbdkResult.getKh();
                //收款方妖码
                String skym=dbdkResult.getSkym();
                //收款方店名
                String skdm=dbdkResult.getSkdm();
                //辅助核算店名
                String fzhsdm=dbdkResult.getFzhsdm();

                String ksbm = "";

                //根据店名查询客商辅助核算编码
                String json = "{\"custname\":\"" + fzhsdm + "\"}";
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("trantype", "code");
                // 系统编码
                headers.add("system", "001");
                // 用户
                headers.add("usercode", "15253172037");
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                HttpEntity<String> formEntitys = new HttpEntity<String>(json, headers);
                String urls = "http://124.70.28.147:8089/u8cloud/api/uapbd/custdoc/query";

                Yfd yfd = restTemplate.postForEntity(urls, formEntitys, Yfd.class).getBody();
                JSONObject resultObject = JSON.parseObject(yfd.getData());
                JSONArray jsonArray = resultObject.getJSONArray("datas");
                JSONObject jsonObject;
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        jsonObject = jsonArray.getJSONObject(0);
                        Ksda.DatasBean.ParentvoBean parentvo = jsonObject.getObject("parentvo", Ksda.DatasBean.ParentvoBean.class);
                        ksbm = parentvo.getCustcode();
                    }
                }
//                RestTemplate restTemplate = new RestTemplate();
//                HttpHeaders headers = new HttpHeaders();
//                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("trantype", "code");
                // 系统编码
                headers.add("system", "001");
                // 用户
                headers.add("usercode", "15253172037");
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                StringBuilder sb=new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");

                //调拨打款凭证
                sb.append("                {\n" +
                        "                    \"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+skym+"'\n" +
                        "                        },\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"96\",\n" +
                        "                            \"checkvaluecode\":"+yhk+"\n" +
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"\",\n" +
                        "                    \"debitamount\":\""+tbje+"\",\n" +
                        "                    \"explanation\":\"收调拨\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"100202\",\n" +
                        "                    \"pk_currtype\":\"CNY\"\n" +
                        "                }," +
                        "{\n" +
                        "\t\t\t\t\"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+skym+"'\n" +
                        "                        },\n" +
                        "\t\t\t\t\t\t{\n" +
                        "                            \"checktypecode\":\"73\",\n" +
                        "                            \"checkvaluecode\":'"+ksbm+"'\n" +//客商辅助核算编码
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\""+tbje+"\",\n" +
                        "                    \"creditquantity\":\"\",\n" +
                        "                    \"debitamount\":\"\",\n" +
                        "                    \"debitquantity\":\"\",\n" +
                        "                    \"detailindex\":\"\",\n" +
                        "                    \"excrate1\":\"\",\n" +
                        "                    \"explanation\":\"收调拨\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"123107\",\n" +
                        "                    \"pk_currtype\":\"CNY\",\n" +
                        "                    \"price\":\"\"\n" +
                        "                },\n");
                sb.append("            ],\n" +
                        "            \"pk_corp\":"+bh+",\n" +
                        "            \"pk_glorgbook\":\""+bh+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");
                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String status = jo.get("status").getAsString();

                if(status.equals("falied")){
                    String errormsg = jo.get("errormsg").getAsString();
                    BtyDbdk dbdk=btyDbdkService.getOne(new QueryWrapper<BtyDbdk>().eq("skdm",skdm).eq("fzhsdm",fzhsdm));
                    if(ToolUtil.isNotEmpty(dbdk)){
                        dbdk.setErrormsg(errormsg);
                        btyDbdkService.updateById(dbdk);
                    }
                }else{
                    BtyDbdk dbdk=btyDbdkService.getOne(new QueryWrapper<BtyDbdk>().eq("skdm",skdm).eq("fzhsdm",fzhsdm));
                    if(ToolUtil.isNotEmpty(dbdk)){
                        dbdk.setFlag(1);
                        btyDbdkService.updateById(dbdk);
                    }
                }
            }


        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

    @RequestMapping("/listSearchExport")
    @ResponseBody
    public List<BtyDbdkResult> listSearchExport (BtyDbdkParam param){
        List<BtyDbdkResult> list= btyDbdkService.customList(param);
        return list;
    }

}


